package com.exam.examtest.util

import android.app.Activity
import androidx.appcompat.app.AppCompatActivity
import java.util.*

/**
 * ClassName ActivityStack
 * Create by rhf
 * Create on 2021/3/30 11:52
 * Description activity堆栈管理
 */
class ActivityStack {

    var mActivityStack: Stack<AppCompatActivity>

    init {
        mActivityStack = Stack()
    }

    companion object {
        @JvmField
        var mSingleInstance: ActivityStack? = null

        @JvmStatic
        fun getInstance(): ActivityStack {
            if (null == this.mSingleInstance) {
                mSingleInstance = ActivityStack()
            }
            return mSingleInstance as ActivityStack
        }
    }

    fun getStack(): Stack<AppCompatActivity> {
        return mActivityStack
    }


    /**
     * 入栈
     *
     * @author WWY
     */
    fun addActivity(activity: AppCompatActivity) {
        mActivityStack.push(activity)
    }

    /**
     * 出栈
     *
     * @author WWY
     */
    fun removeActivity(activity: AppCompatActivity) {
        mActivityStack.remove(activity)
    }

    /**
     * 彻底退出
     *
     * @author WWY
     */
    fun finishAllActivity() {
        var activity: AppCompatActivity?
        while (!mActivityStack.empty()) {
            activity = mActivityStack.pop()
            activity?.finish()
        }
    }

    /**
     * finish指定的activity
     *
     * @author WWY
     */
    fun finishActivity(actCls: Class<out AppCompatActivity>): Boolean {
        val act = findActivityByClass(actCls)
        if (null != act && !act.isFinishing) {
            act.finish()
            return true
        }
        return false
    }

    fun findActivityByClass(actCls: Class<out AppCompatActivity>): Activity? {
        var aActivity: AppCompatActivity? = null
        val itr = mActivityStack.iterator()
        while (itr.hasNext()) {
            aActivity = itr.next()
            if (null != aActivity && aActivity.javaClass.name == actCls.name && !aActivity.isFinishing) {
                break
            }
            aActivity = null
        }
        return aActivity
    }

    /**
     * finish指定的activity之上的所有activity
     *
     * @author WWY
     */
    fun finishToActivity(actCls: Class<out AppCompatActivity>, isIncludeSelf: Boolean): Boolean {
        val buf = ArrayList<AppCompatActivity>()
        val size = mActivityStack.size
        var activity: AppCompatActivity? = null
        for (i in size - 1 downTo 0) {
            activity = mActivityStack[i]
            if (activity!!.javaClass.isAssignableFrom(actCls)) {
                for (a in buf) {
                    a.finish()
                }
                return true
            } else if (i == size - 1 && isIncludeSelf) {
                buf.add(activity)
            } else if (i != size - 1) {
                buf.add(activity)
            }
        }
        return false
    }

}